package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisData;
import jdk.jfr.BooleanFlag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    private static final ExecutorService CAHE_REBUILD_EXECUTORY = Executors.newFixedThreadPool(10);

    @Override
    public Result queryById(Long id) {
        // 缓存穿透
        Shop shop = queryWithPassThrough(id);

        // 缓存击穿(互斥锁)
        Shop shop1 = queryWithMutex(id);

        // 缓存击穿(逻辑过期)
        Shop shop2 = queryWithLogicalExpire(id);

        return Result.ok(shop);
    }

    // 缓存穿透
    public Shop queryWithPassThrough(Long id){
        String key = CACHE_SHOP_KEY + id;
        // 查找redis中是否存在商铺缓存
        String s = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(s)){
            // 若存在，让string转为json返回
            return JSONUtil.toBean(s, Shop.class);
        }
        // 从上面返回的可能是null也可能是""
        // 判断s是否为空值
        if(s != null){
            return null;
        }
        // 不存在就查找后保存redis返回
        Shop shop = getById(id);
        if(shop == null){
            // 将空值写入redis, 防止缓存穿透
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        // 对象转为json字符串，并设置过期时间为30分钟
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return null;
    }

    // 缓存击穿(互斥锁)
    public Shop queryWithMutex(Long id){
        String key = CACHE_SHOP_KEY + id;
        // 查找redis中是否存在商铺缓存
        String s = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(s)){
            // 若存在，让string转为json返回
            return JSONUtil.toBean(s, Shop.class);
        }
        // 从上面返回的可能是null也可能是""
        // 判断s是否为空值
        if(s != null){
            return null;
        }
        // 获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        try {
            boolean isLock = tryLock(lockKey);
            // 未获取锁，就先休眠在来获取锁
            if(!isLock){
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            // 不存在就查找后保存redis返回
            Shop shop = getById(id);
            // 模拟重建的延迟
            Thread.sleep(200);
            if(shop == null){
                // 将空值写入redis, 防止缓存穿透
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            // 对象转为json字符串，并设置过期时间为30分钟
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e){
            throw new RuntimeException(e);
        } finally {
            // 释放锁
            unLock(lockKey);
        }
        return null;
    }

    // 缓存击穿(逻辑过期)
    public Shop queryWithLogicalExpire(Long id){
        String key = CACHE_SHOP_KEY + id;
        // 查找redis中是否存在商铺缓存
        String s = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isBlank(s)){
            // 若存在，返回null
            return null;
        }

        // 判断逻辑日期是否过期
        // Json反序列化为对象
        RedisData redisData = JSONUtil.toBean(s, RedisData.class);
        // 先转为Json对象，再把json对象转回来
        JSONObject data = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class);
        // 判断是否过期
        LocalDateTime time = redisData.getExpireTime();
        if(time.isAfter(LocalDateTime.now())){
            // 未过期就直接返回
            return shop;
        }
        // 已过期就需要缓存重建
        // 获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        if(isLock){
            // 如果获取锁成功，就开启独立线程
            CAHE_REBUILD_EXECUTORY.submit(()->{
                try {
                    // 实现缓存重建
                    this.saveShopReids(id, 30L);
                } catch (Exception e){
                    throw new RuntimeException(e);
                } finally {
                    // 释放缓存
                    unLock(lockKey);
                }

            });
        }
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return null;
    }



    @Override
    // 事务管理
    @Transactional
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if(id == null){
            return Result.fail("店铺的id不能为空");
        }
        // 更新数据库
        updateById(shop);
        // 删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);

        return Result.ok();

    }

    // 获取锁
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    // 释放锁
    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }

    // 封装逻辑过期时间
    private void saveShopReids(Long id, Long expireTime) throws InterruptedException{
        Shop shop = getById(id);
        // 模拟延迟
        Thread.sleep(200);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireTime));
        // 写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

}
